package com.example.xpagedemoproject.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FragmentAdapter<T extends Fragment> extends FragmentPagerAdapter {
    private List<T> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    public FragmentAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    public FragmentAdapter(FragmentManager fm, List<T> fragments){
        super(fm);
        setFragments(fragments);
    }

    public FragmentAdapter(FragmentManager fm,T[] fragments){
        super(fm);
        setFragments(Arrays.asList(fragments));
    }

    private FragmentAdapter setFragments(List<T> fragments) {
        if (fragments != null && fragments.size() > 0) {
            fragments.clear();
            fragments.addAll(fragments);
        }
        return this;
    }

    public FragmentAdapter addFragments(List<T> fragments){
        if (fragments != null && fragments.size() > 0) {
            fragments.addAll(fragments);
        }
        return this;
    }

    public FragmentAdapter setTitles(List<String> titles){
        if (titles != null && titles.size() > 0) {
            titles.clear();
            titles.addAll(titles);
        }
        return this;
    }
    public FragmentAdapter addTitles(List<String> titles){
        if (titles != null && titles.size() > 0) {
            titles.addAll(titles);
        }
        return this;
    }

    public FragmentAdapter addFragment(T fragment,String title){
        if (fragment != null) {
            fragments.add(fragment);
            titles.add(title);
        }
        return this;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

    public List<T> getFragments() {
        return fragments;
    }

    public List<String> getTitles() {
        return titles;
    }
}
